package com.example.jetpacktest.coroutine

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.select
import org.junit.Test

class Test007 {

    private fun CoroutineScope.f001(): ReceiveChannel<String> {
        return produce<String>{
            while(true){
                delay(100)
                send("xxx")
            }
        }
    }


    private fun CoroutineScope.f002() = produce<String> {
        while(true){
            delay(300)
            send("yyyy")
        }
    }


    private suspend fun f003(ch1: ReceiveChannel<String>, ch2: ReceiveChannel<String>){
        select<Unit> {
            ch1.onReceive{
                println(it)
            }
            ch2.onReceive{
                println(it)
            }
        }
    }

    @Test
    fun test001() = runBlocking {
        val x = f001()
        val y = f002()
        val job = launch {
            repeat(20){
                f003(x, y)
            }
        }
        job.join()
        //coroutineContext.cancelChildren()
    }


    private fun CoroutineScope.f004(ch: SendChannel<Int>): ReceiveChannel<Int> = produce<Int> {
        for(i in 1..10){
            delay(100)
            select<Unit> {
                onSend(i){}
                ch.onSend(i){

                }
            }
        }
    }


    @Test
    fun test002() = runBlocking {
        val ch1 = Channel<Int>()
        val ch2 = f004(ch1)
        val job1 = launch {
            ch1.consumeEach {
                println("快...$it")
            }
        }

        val job2 = launch {
            ch2.consumeEach {
                delay(300)
                println("慢........$it")
            }
        }
        //job1.join()
        //job2.join()
        delay(10000)
        coroutineContext.cancelChildren()
        println("done")

    }


}